﻿@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.JSInterop
@using DaoHang.Components.Shared
@inject NavigationManager NavigationManager

<Router AppAssembly="typeof(Program).Assembly">
    <Found Context="routeData">
        @{
            var isAdminRoute = routeData.PageType.Namespace?.Contains("Admin") == true ||
                               routeData.PageType.FullName?.Contains("Pages.Admin") == true ||
                               routeData.PageType.Name == "Admin" ||
                               routeData.PageType.FullName?.Contains("Admin.razor") == true;
        }

        @if (isAdminRoute && routeData.PageType.FullName?.Contains("Login") != true)
        {
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(Layout.MainLayout)">
                <NotAuthorized>
                    <RedirectToLogin />
                </NotAuthorized>
            </AuthorizeRouteView>
        }
        else
        {
            <RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
        }
        <FocusOnNavigate RouteData="routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>找不到页面</PageTitle>
        <LayoutView Layout="@typeof(Layout.MainLayout)">
            <div class="container py-5">
                <div class="text-center">
                    <h1 class="display-4">404</h1>
                    <p class="lead">抱歉，您请求的页面不存在。</p>
                    <a href="/" class="btn btn-primary">返回首页</a>
                </div>
            </div>
        </LayoutView>
    </NotFound>
</Router>

@code {
    /// <summary>
    /// 重定向到登录页的组件
    /// </summary>
    public class RedirectToLogin : ComponentBase
    {
        [Inject]
        public required NavigationManager NavigationManager { get; set; }

        protected override void OnInitialized()
        {
            NavigationManager.NavigateTo("/admin/login", true);
        }
    }
}
